package com.smh.mp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.smh.mp.domain.dto.PageDTO;
import com.smh.mp.domain.po.Address;
import com.smh.mp.domain.query.UserQuery;
import com.smh.mp.domain.vo.AddressVO;
import com.smh.mp.domain.vo.UserVO;
import com.smh.mp.enums.UserStatus;
import com.smh.mp.mapper.UserMapper;
import com.smh.mp.domain.po.User;
import com.smh.mp.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final UserMapper userMapper;

    @Override
    @Transactional
    public void reduceMoneyById(Long id, Integer money) {
        //查询用户状态
//        User user = userMapper.selectById(id);
        User user = getById(id);
//        User user = baseMapper.selectById(id);
        if (user == null || user.getStatus() == UserStatus.FREEZE) {
            throw new RuntimeException("用户状态异常");
        }
        //查询用户的余额是否充足
        if (user.getBalance() < money) {
            throw new RuntimeException("用户余额不足");
        }
        int nowMoney = user.getBalance() - money;
        lambdaUpdate()
                .set(User::getBalance, nowMoney)
                .set(nowMoney == 0, User::getStatus, UserStatus.FREEZE)
                .eq(User::getId, id)
                .eq(User::getBalance, user.getBalance())
                .update();

        //修改用户的余额
//        LambdaUpdateWrapper wrapper = new LambdaUpdateWrapper<User>()
//                .eq(User::getId, id);
//        userMapper.reduceMoneyById(wrapper, money);
    }

    @Override
    public List<UserVO> queryUsers(String name, Integer status, Integer maxBalance, Integer minBalance) {

        //模糊匹配姓名,匹配状态,以及资产的范围
//        LambdaQueryChainWrapper<User> wrapper
        List<User> userList = lambdaQuery()
                .like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .ge(minBalance != null, User::getBalance, minBalance)
                .le(maxBalance != null, User::getBalance, maxBalance)
                .list();
//        List<User> users = baseMapper.selectList(wrapper);
        List<UserVO> userVOList = userList.stream().map(user -> BeanUtil.copyProperties(user, UserVO.class)).collect(Collectors.toList());
        return userVOList;
    }

    @Override
    public UserVO queryUserAndAddressById(Long id) {

        User user = getById(id);
        if (user == null || user.getStatus() == UserStatus.FREEZE) {
            throw new RuntimeException("用户状态异常");
        }
        List<Address> list = Db.lambdaQuery(Address.class).eq(Address::getUserId, id).list();
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
//        List<AddressVO> addressVOList = list.stream().map(address -> BeanUtil.copyProperties(address, AddressVO.class)).collect(Collectors.toList());
        List<AddressVO> addressVOList = BeanUtil.copyToList(list, AddressVO.class);
        userVO.setAddressVOList(addressVOList);
        return userVO;
    }

    @Override
    public List<UserVO> queryUserAndAddressByIds(List<Long> ids) {
        //效率比较低
/*        List<User> users = listByIds(ids);
        if (users == null) {
            return Collections.emptyList();
        }

        List<UserVO> userVOList = BeanUtil.copyToList(users, UserVO.class);
        for (UserVO userVO : userVOList) {
            if (userVO == null || userVO.getStatus() == 2) {
                throw new RuntimeException("用户状态异常");
            }
            List<Address> addressList = Db.lambdaQuery(Address.class).eq(Address::getUserId, userVO.getId()).list();
            List<AddressVO> addressVOList = BeanUtil.copyToList(addressList, AddressVO.class);
            userVO.setAddressVOList(addressVOList);
        }*/

        List<User> userList = listByIds(ids);
        if (userList == null) {
            return Collections.emptyList();
        }

        List<Address> addressList = Db.lambdaQuery(Address.class).in(Address::getUserId, ids).list();

        Map<Long, List<AddressVO>> map = new HashMap<>();
        if (addressList != null) {
            List<AddressVO> addressVOList = BeanUtil.copyToList(addressList, AddressVO.class);
            map = addressVOList.stream().collect(Collectors.groupingBy(AddressVO::getUserId));
        }

        List<UserVO> userVOList = BeanUtil.copyToList(userList, UserVO.class);
        for (UserVO userVO : userVOList) {
            userVO.setAddressVOList(map.get(userVO.getId()));
        }

        return userVOList;
    }

    @Override
    public PageDTO<UserVO> pageQueryUsers(UserQuery userQuery) {

        String name = userQuery.getName();
        Integer status = userQuery.getStatus();
        //构建page对象
//        //页码,页面大小
//        Page<User> page = Page.of(userQuery.getPageNo(), userQuery.getPageSize());
//        //排序条件
//        page = page.addOrder(new OrderItem().setColumn(userQuery.getSortBy()).setAsc(userQuery.getIsAsc()));
        Page<User> page = userQuery.toMpPage();
        //查询数据
        page = lambdaQuery()
                .like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .page(page);

        //封装返回对象
//        PageDTO<UserVO> userVOPageDTO = new PageDTO<>();
//
//        userVOPageDTO.setTotal(page.getTotal());
//        userVOPageDTO.setPages(page.getPages());
//        userVOPageDTO.setList(BeanUtil.copyToList(page.getRecords(), UserVO.class));
        //指定转化的VO对象的字节码文件
//        PageDTO<UserVO> userVOPageDTO = PageDTO.of(page, UserVO.class);
        //自己写PO到VO的转化逻辑
        PageDTO<UserVO> userVOPageDTO = PageDTO.of(page, user -> {
//            UserVO userVO = new UserVO();
//            userVO.setId(user.getId());
            return BeanUtil.copyProperties(user, UserVO.class);
        });


        return userVOPageDTO;
    }
}
